//
//  RMPasswordViewController.m
//  rmplanner
//
//  Created by cs321ga3 on 9/10/12.
//  Copyright (c) 2012 BOSS Systems. All rights reserved.
//

#import "RMPasswordViewController.h"
#import <CommonCrypto/CommonDigest.h>

@interface RMPasswordViewController ()

@property (strong, nonatomic) NSMutableData* retData;

@end

@implementation RMPasswordViewController

@synthesize old, password, retype, retData;

#pragma mark UITableViewController functions

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
		return (interfaceOrientation == UIInterfaceOrientationPortrait);
	else
		return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

#pragma mark UITextField delegate functions

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	if (textField == retype)
		[textField resignFirstResponder];
	else if (textField == old)
	{
		[textField resignFirstResponder];
		[password becomeFirstResponder];
	}
	else
	{
		[textField resignFirstResponder];
		[retype becomeFirstResponder];
	}
	return YES;
}

#pragma mark Interface Builder actions
- (IBAction)save
{
	if ([[self hash:old.text] isEqualToString:[[NSUserDefaults standardUserDefaults] valueForKey:@"password"]])
	{
		if ([retype.text isEqualToString:password.text])
		{
			NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/changePassword"];
			NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
			NSData* data = [[NSString stringWithFormat:@"user_id=%d&oldpass=%@& newpass=%@", [[NSUserDefaults standardUserDefaults] integerForKey:@"uid"], [self hash:old.text], [self hash:password.text]] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
			[request setHTTPBody:data];
			[request setHTTPMethod:@"POST"];
			NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
			NSAssert((connection != nil), @"Failed to create a connection");
			[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		}
		else
		{
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Password mismatch" message:@"Retyped password does not match new password. Please re-enter your new password" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alertView show];
		}
	}
	else
	{
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Password mismatch" message:@"Old password does not match current password. Please retype your current password" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
	}
}

#pragma mark NSURLConnectionDelegate functions
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	retData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[retData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSString* str = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
	if ([str isEqualToString:@"good"])
	{
		[[NSUserDefaults standardUserDefaults] setValue:[self hash:password.text] forKey:@"password"];
		[self.navigationController popViewControllerAnimated:YES];
	}
	else
	{
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Could not connect to server. Your password has not been changed. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSLog(@"%@", [error description]);
	connection = nil;
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:@"Connection to server failed. Your password has not been changed. Please try again later" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alertView show];
}

#pragma mark Hash function

- (NSString *)hash:(NSString *)str;
{
	// place the string into a UTF-8 c-string, then hash it
	const char* ptr = [str UTF8String];
	unsigned char md5buffer[CC_MD5_DIGEST_LENGTH];
	CC_MD5(ptr, strlen(ptr), md5buffer);
	
	// place the hashed c-string into a new NSString
	NSMutableString* output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
	for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
		[output appendFormat:@"%02x", md5buffer[i]];
	
	// return the string object
	return output;
}

@end
